package aash.utils.xml;

import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.xpath.XPath;

/**
 * Class containing tools for parsing XML documents (JDOM).
 * @author Aashintan
 */
public class ParsingXml {
    /**
     * Logger.
     */
    private static Logger log = Logger.getLogger(ParsingXml.class.getName());

    /**
     * Return a list of values targeted by XPATH expression.
     * @param xmlDocument to parse
     * @param xpath the path to targeted element
     * @param attribute the attribute to read
     * @return a list of values of the attribute
     */
    public static List < String > getAttributesList(final Document xmlDocument, final String xpath,
    final String attribute) {
        List < String > attributes = new ArrayList < String >();
        Element root = xmlDocument.getRootElement();
        try {
            XPath xpa = XPath.newInstance(xpath);
            List < Element > elements = xpa.selectNodes(root);
            for (int i = 0; i < elements.size(); i++) {
                attributes.add(elements.get(i).getAttributeValue(attribute));
            }
        } catch (JDOMException e) {
            log.error("Error during XML parsing : " + e);
        }
        return attributes;
    }

    /**
     * Return the value targeted by XPATH expression.
     * @param xmlDocument to parse
     * @param xpath the path to targeted element
     * @param attribute the attribute to read
     * @return the value of the attribute
     */
    public static String getAttributeValue(final Document xmlDocument, final String xpath,
    final String attribute) {
        String value = null;
        if (xmlDocument != null && xpath != null) {
            Element root = xmlDocument.getRootElement();
            try {
                XPath xpa = XPath.newInstance(xpath);
                Element attributeValue = (Element) xpa.selectSingleNode(root);
                if ("".equals(attributeValue)) {
                    attributeValue = null;
                }
                value = attributeValue.getAttributeValue(attribute);
            } catch (JDOMException e) {
                log.error("Error during XML parsing : " + e);
            }
        }
        return value;
    }
}
